﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using XChip_Common;
using XChipTool.Enties;

namespace XChipTool
{
    public partial class XChip_ToolBox : UserControl
    {
        public XChip_ToolBox()
        {
            InitializeComponent();
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            #region 判断是否有内容 无内容就不生成
            if (string.IsNullOrEmpty(textEdit1.Text) || string.IsNullOrEmpty(textEdit2.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("缺少文件", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            #endregion


            switch (radioGroup1.SelectedIndex)
            {
                case 0:
                    SettingAndPatchConcat(textEdit1.Text,textEdit2.Text);
                    break;
                case 1:
                    TvrToCarProgram(textEdit1.Text, textEdit2.Text);
                    break;
                default:
                    break;

            }
           
        }

        private List<string> GetList(string[] listS, int startIndex , int endIndex)
        {
            List<string> listTemp = new List<string>();
            for (int i = startIndex; i <= endIndex; i++)
            {
                listTemp.Add(listS[i]);
            }
            return listTemp;
        }

        //1.先取AHD1080p_pal25fps_setting的step0~step2的2.44；
        //2.再取xchip_IQ_common_setting的step2的2.5~step3的3.1；
        //3.再取AHD1080p_pal25fps_setting的step3的3.2~step4的4.6；
        //4.再取xchip_IQ_common_setting的step4的4.7；
        //5.再取AHD1080p_pal25fps_setting的step的4.9~step7;
        //6.再取xchip_IQ_common_setting的step8;
        //7.再取AHD1080p_pal25fps_setting的bypass~patch_regs;
        //8.再取xchip_IQ_common_setting的step9;
        //9.再取AHD1080p_pal25fps_setting的step9至结束；
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filePath1">Common路径</param>
        /// <param name="filePath2">Setting路径</param>
        private void TvrToCarProgram(string filePath1, string filePath2)
        {
            //StreamReader srC = new StreamReader(filePath1, Encoding.Default);
            //StreamReader srS = new StreamReader(filePath2, Encoding.Default);           
           
            List<string> listStr = new List<string>();
            string[] listC = File.ReadAllLines(filePath1,Encoding.Default);
            string[] listS = File.ReadAllLines(filePath2, Encoding.Default);
            int startIndexS = -1;
            int endIndexS = -1;
            int startIndexC = -1;
            int endIndexC = -1;

            //1.先取AHD1080p_pal25fps_setting的step0~step2的2.44；
            startIndexS = 0;            
            endIndexS = Array.FindIndex(listS, startIndexS, t => t.IndexOf("Step 3 config psram", StringComparison.InvariantCultureIgnoreCase) >= 0)-2;
            if (endIndexS < 0)
            {
                endIndexS = Array.FindIndex(listS, startIndexS, t => t.IndexOf("Step 4 config isp", StringComparison.InvariantCultureIgnoreCase) >= 0) - 1;
            }
            if(startIndexS<0 || endIndexS < 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("1.setting中未找到‘Step 3 config psram’或‘Step 4 config isp’", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            listStr.AddRange(GetList(listS, startIndexS, endIndexS));

            //2.再取xchip_IQ_common_setting的step2的2.5~step3的3.1；
            startIndexC= Array.FindIndex(listC,  t => t.IndexOf("2.5 config pad", StringComparison.InvariantCultureIgnoreCase) >= 0);
            endIndexC = Array.FindIndex(listC,startIndexC, t => t.IndexOf("Step 4 config isp", StringComparison.InvariantCultureIgnoreCase) >= 0) -1;
            if(startIndexC<0 || endIndexC < 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("2.common中未找到‘2.5 config pad’或‘Step 4 config isp’", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            listStr.AddRange(GetList(listC, startIndexC, endIndexC));

            //3.再取AHD1080p_pal25fps_setting的step3的3.2~step4的4.6；
            startIndexS = Array.FindIndex(listS, endIndexS, t => t.IndexOf("3.2 config nr3d and dvp2avalon", StringComparison.InvariantCultureIgnoreCase) >= 0);
            if (startIndexS < 0)
            {
                startIndexS = Array.FindIndex(listS, endIndexS, t => t.IndexOf("Step 4 config isp", StringComparison.InvariantCultureIgnoreCase) >= 0);
            }
            endIndexS = Array.FindIndex(listS, startIndexS, t => t.IndexOf("4.9-UTC config", StringComparison.InvariantCultureIgnoreCase) >= 0) - 1;
            if (startIndexS < 0 || endIndexS < 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("3.setting中未找到‘3.2 config nr3d and dvp2avalon’或‘Step 4 config isp’或‘4.9-UTC config’", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            listStr.AddRange(GetList(listS, startIndexS, endIndexS));

            //4.再取xchip_IQ_common_setting的step4的4.7；
            startIndexC = Array.FindIndex(listC,endIndexC, t => t.IndexOf("4.7-OSD_Mirror", StringComparison.InvariantCultureIgnoreCase) >= 0);
            endIndexC = Array.FindIndex(listC, startIndexC ,t => t.IndexOf("Step 8 config gpio", StringComparison.InvariantCultureIgnoreCase) >= 0) - 1;
            if (startIndexC < 0 || endIndexC < 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("4.common中未找到‘4.7-OSD_Mirror’或‘Step 8 config gpio’", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            listStr.AddRange(GetList(listC, startIndexC, endIndexC));

            //5.再取AHD1080p_pal25fps_setting的step的4.9~step7;
            startIndexS = endIndexS+1;           
            endIndexS = Array.FindIndex(listS, startIndexS, t => t.IndexOf("config xchip_i2c_bypass", StringComparison.InvariantCultureIgnoreCase) >= 0) - 3;
            if (startIndexS < 0 || endIndexS < 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("5.setting中未找到‘config xchip_i2c_bypass’", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            listStr.AddRange(GetList(listS, startIndexS, endIndexS));

            //6.再取xchip_IQ_common_setting的step8;
            startIndexC = endIndexC+1;
            endIndexC = Array.FindIndex(listC, startIndexC, t => t.IndexOf("config xchip_IQ_regs", StringComparison.InvariantCultureIgnoreCase) >= 0) - 1;
            if (startIndexC < 0 || endIndexC < 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("6.common中未找到‘config xchip_IQ_regs’", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            listStr.AddRange(GetList(listC, startIndexC, endIndexC));

            //7.再取AHD1080p_pal25fps_setting的bypass~patch_regs;
            startIndexS = endIndexS + 3;
            endIndexS = Array.FindIndex(listS, startIndexS, t => t.IndexOf("config xchip_IQ_regs", StringComparison.InvariantCultureIgnoreCase) >= 0) - 1;
            if (startIndexS < 0 || endIndexS < 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("7.setting中未找到‘config xchip_IQ_regs’", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            listStr.AddRange(GetList(listS, startIndexS, endIndexS));

            //8.再取xchip_IQ_common_setting的step9;
            startIndexC = endIndexC + 1;
            endIndexC = Array.FindIndex(listC, startIndexC, t => t.IndexOf("IQ_End", StringComparison.InvariantCultureIgnoreCase) >= 0) - 1;
            if (startIndexC < 0 || endIndexC < 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("8.common中未找到‘IQ_End’", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            listStr.AddRange(GetList(listC, startIndexC, endIndexC));

            //9.再取AHD1080p_pal25fps_setting的step9至结束；
            startIndexS = Array.FindIndex(listS, endIndexS, t => t.IndexOf("9.2 IQ_oneself", StringComparison.InvariantCultureIgnoreCase) >= 0);
            endIndexS = listS.Count() - 1;
            if (startIndexS < 0 || endIndexS < 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("9.setting中未找到‘IQ_oneself’", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            listStr.AddRange(GetList(listS, startIndexS, endIndexS));
            

            SaveFileDialog sfDialog = new SaveFileDialog();
            sfDialog.Filter = "TXT Files(*.txt;*.c)|*.txt;*.c|All Files(*.*)|*.*";            
            sfDialog.RestoreDirectory = false;
            sfDialog.FileName = Path.GetFileNameWithoutExtension(filePath2) + "_addIQ_"+ DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
            if (sfDialog.ShowDialog() == DialogResult.OK)
            {
               
                File.WriteAllLines(sfDialog.FileName, listStr, Encoding.Default);
                DevExpress.XtraEditors.XtraMessageBox.Show("合并完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }   
        }
        /// <summary>
        /// Setting 和Patch合并
        /// </summary>
        /// <param name="filePath1">setting路径</param>
        /// <param name="filePath2">patch路径</param>
        private void SettingAndPatchConcat(string filePath1, string filePath2)
        {
            #region 处理patch文件
            StreamReader srP = new StreamReader(filePath2, Encoding.Default);
            string str;
            List<string> patchStr = new List<string>();
            bool mask = true;//标值是否需要处理，false为不需要处理，true为需要
            while (null != (str = srP.ReadLine()))
            {
                if (str.Contains("0x0006"))
                    mask = false;
                if (mask)
                {
                    if (str.Contains("0xffff, 0xfef") || str.Contains("[paralist]") || string.IsNullOrEmpty(str))
                    {
                        continue;
                    }
                    string[] tempstr = str.Split(',');
                    if (tempstr.Count() >= 2 && tempstr[1].Length >= 6)
                    {
                        tempstr[1] = " 0x" + (Convert.ToUInt32(tempstr[1].Trim().Replace("0x", ""), 16) & 0xff).ToString("X2");
                        str = string.Join(",", tempstr);
                    }
                }
                patchStr.Add(str);
            }
            srP.Close();
            if (patchStr.Count != 0)
            {
                patchStr.Add("\n0xfffe, 0x50,\n0x0137, 0x99,\n");
            }

            #endregion
            StreamReader sr = new StreamReader(filePath1, Encoding.Default);
            List<string> settStr = new List<string>();
            while (null != (str = sr.ReadLine()))
            {
                settStr.Add(str.ToString());
            }
            sr.Close();
            //查找 Patch_start 开始  Patch_End 结束位置
            var startIndex = Array.FindIndex(settStr.ToArray(), t => t.IndexOf("Patch_start", StringComparison.InvariantCultureIgnoreCase) >= 0);
            var endIndex = Array.FindIndex(settStr.ToArray(), t => t.IndexOf("Patch_End", StringComparison.InvariantCultureIgnoreCase) >= 0);
            var countIndex = (endIndex + 1) - (startIndex + 1);
            if (startIndex == -1 || endIndex == -1)
            {
                //setShowMsg("无法找到\"Patch_Start\"或\"Patch_End\"，请先设置");
                DevExpress.XtraEditors.XtraMessageBox.Show("无法找到\"Patch_Start\"或\"Patch_End\"，请先设置", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            settStr.InsertRange(startIndex + 1, patchStr);
            SaveFileDialog sfDialog = new SaveFileDialog();
            sfDialog.Filter = "TXT Files(*.txt;*.c)|*.txt;*.c|All Files(*.*)|*.*";
            //sfDialog.InitialDirectory = Path.GetDirectoryName(sett0Model.BinInPath);//setting区的binIn路径会在更新iq或控制后指向"/settingTemp"下，所以注释
            sfDialog.RestoreDirectory = false;
            sfDialog.FileName = Path.GetFileNameWithoutExtension(filePath1) + "_" + Path.GetFileNameWithoutExtension(filePath2) + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".c";
            if (sfDialog.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllLines(sfDialog.FileName, settStr);
                //WriteListToTextFileOverwrite(settStr, sfDialog.FileName);
                DevExpress.XtraEditors.XtraMessageBox.Show("合并完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "TXT Files(*.txt;*.c)|*.txt;*.c|All Files(*.*)|*.*";
            ofd.RestoreDirectory = false;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                textEdit1.Text = ofd.FileName;
            }
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "TXT Files(*.txt;*.c)|*.txt;*.c|All Files(*.*)|*.*";
            ofd.RestoreDirectory = false;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                textEdit2.Text = ofd.FileName;
            }
        }       

        private void radioGroup1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (radioGroup1.SelectedIndex)
            {
                case 0://SettingAndPatch
                    labelControl1.Text = "Setting";
                    labelControl2.Text = "Patch";
                    break;
                case 1://TvrToCar
                    labelControl1.Text = "Common";
                    labelControl2.Text = "Setting";
                    break;
                default:
                    break;
            }
        }

        private void btn_SelectSettingA_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "TXT Files(*.txt;*.c)|*.txt;*.c|All Files(*.*)|*.*";
            ofd.RestoreDirectory = false;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                txt_SettingA.Text = ofd.FileName;
            }
        }

        private void btn_SelectSettingb_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "TXT Files(*.txt;*.c)|*.txt;*.c|All Files(*.*)|*.*";
            ofd.RestoreDirectory = false;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                txt_SettingB.Text = ofd.FileName;
            }
        }

        private void btn_Transplant_Click(object sender, EventArgs e)
        {
            List<string> settingAList = File.ReadAllLines(txt_SettingA.Text, Encoding.Default).ToList() ;
                    
            #region 1.取出A的10.1部分
            int aStartIndex = settingAList.FindIndex(c => c.ToLower().Contains("//10.1 iq_common"));
            if (aStartIndex == -1)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("未在SettingA中找到\"//10.1 IQ_common\"", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            int aEndIndex = settingAList.FindIndex(c => c.ToLower().Contains("//10.2 iq_oneself"));
            if (aEndIndex == -1)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("未在SettingA中找到\"//10.2 IQ_oneself\"", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            List<string> iqCommonList = settingAList.Where((c, index) => index > aStartIndex && index < aEndIndex).ToList();
            #endregion

            List<string> settingBList = File.ReadAllLines(txt_SettingB.Text, Encoding.Default).ToList();
            #region 2.移除B的10.1部分
            int bStartIndex = settingBList.FindIndex(c => c.ToLower().Contains("//10.1 iq_common"));
            if (bStartIndex == -1)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("未在SettingB中找到\"//10.1 IQ_common\"", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            int bEndIndex = settingBList.FindIndex(c => c.ToLower().Contains("//10.2 iq_oneself"));
            if (bEndIndex == -1)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("未在SettingBS中找到\"//10.2 IQ_oneself\"", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                settingBList.RemoveRange(bStartIndex + 1, bEndIndex - bStartIndex - 1);
            }
            catch (Exception ex)
            {
                throw;
            }
            #endregion

            #region 3.把A的10.1部分插入到B的对应位置
            settingBList.InsertRange(bStartIndex+1, iqCommonList);
            #endregion

            #region 4.把BList写入文件            
            SaveFileDialog sfDialog = new SaveFileDialog();
            sfDialog.Filter = "TXT Files(*.txt;*.c)|*.txt;*.c|All Files(*.*)|*.*";
            //sfDialog.InitialDirectory = Path.GetDirectoryName(sett0Model.BinInPath);//setting区的binIn路径会在更新iq或控制后指向"/settingTemp"下，所以注释
            sfDialog.RestoreDirectory = false;
            sfDialog.FileName = Path.GetFileNameWithoutExtension(txt_SettingB.Text) + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetExtension(txt_SettingB.Text);
            if(sfDialog.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllLines(sfDialog.FileName, settingBList, Encoding.Default);
                DevExpress.XtraEditors.XtraMessageBox.Show("完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }           
            #endregion
        }


        private void simpleButton4_Click_1(object sender, EventArgs e)
        {
           
            //var list = pCDal.GetList();
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;
            dialog.Filter = "Excel文件(*.xlsx, *.xls) | *.xlsx; *.xls";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                var dt =  NPOIOprateExcel.ExcelToDataTable(dialog.FileName, true);
                parameter_contrastManager pCDal = new parameter_contrastManager();

               var list = ModelConvertHelper<parameter_contrast>.ConvertToModel(dt);
                for (int i = 0; i < list.Count; i++)
                {
                    list[i].SortNum = i;
                }
                pCDal.Deletes(c => true);
                pCDal.Insert(list.ToList());
                DevExpress.XtraEditors.XtraMessageBox.Show("导入完成！");
            }
        }

        private void simpleButton5_Click(object sender, EventArgs e)
        {
           
            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "导出文件（*.xls）|*.xls";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = "模板_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                parameter_contrastManager pCDal = new parameter_contrastManager();
                var list = pCDal.GetList();
                var dt = ModelConvertHelper<parameter_contrast>.ToDataTable(list);
                dt.Columns.Remove("SortNum");
                dt.Columns.Remove("id");
                NPOIOprateExcel.DataTableToExcel(dt, "parameter_contrast", true, sfd.FileName);

            }

        }

        private void simpleButton6_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;
            dialog.Filter = "TXT文件(*.txt, *.c) | *.txt; *.c";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                textEdit3.Text = dialog.FileName;
                var listStr =  NotesHelp.GetFileList(dialog.FileName);
                parameter_contrastManager pCDal = new parameter_contrastManager();
                var list = pCDal.GetList();
                var mlist = list.Select(c => c.Module).Distinct().ToList();
                List<string> mmlist = new List<string>();
                foreach (var item in mlist)
                {
                    var sndex = Array.FindIndex(listStr.ToArray(), t => t.note.IndexOf(item, StringComparison.InvariantCultureIgnoreCase) >= 0);
                    if (sndex != -1)
                    {
                        mmlist.Add(item);
                    }
                }

                //输出文本
                //List<string> sb = new List<string>();
                StringBuilder sb = new StringBuilder();
                sb.Append("#region config xchip_IQ_regs =\n");
                sb.Append("{\n");
                sb.Append("//********** Step 10 IQ setting********************************//\n");
                sb.Append("//IQ_Start\n");
                sb.Append("0xfffd,0x80,\n");
                sb.Append("//10.1 IQ_common\n");
                foreach (var item in list)
                {
                    if (string.IsNullOrEmpty(item.addr)&&string.IsNullOrEmpty(item.ReadAddr))
                    {
                        sb.Append("\n"); sb.Append($"{item.PreNote}\n");
                        continue;
                    }
                    if (!string.IsNullOrEmpty(item.PreNote)) { sb.Append("\n"); sb.Append($"{item.PreNote}\n"); }
                    if (item.addr.Contains("0xff"))
                    {
                        string str = item.RearNote.Contains("\\n") ? $"{item.RearNote.Replace("\\n", "")}\n" : item.RearNote;
                        sb.Append($"{item.addr}{str.Trim()}\n");
                        if (item.RearNote.Contains("\\n")) sb.Append("\n");
                    }
                    else if (item.addr.Contains(","))
                    {
                        string str = item.RearNote.Contains("\\n") ? $"{item.RearNote.Replace("\\n", "")}\n" : item.RearNote;
                        sb.Append($"{item.addr}{str.Trim()}\n");
                        if (item.RearNote.Contains("\\n")) sb.Append("\n");
                    }
                    else if (!string.IsNullOrEmpty(item.addr)&&string.IsNullOrEmpty(item.ReadAddr))
                    {       string str = item.RearNote.Contains("\\n") ? $"{item.RearNote.Replace("\\n", "")}\n" : item.RearNote;
                            sb.Append($"{item.addr},0x  ,{str.Trim()}\n");
                        if (item.RearNote.Contains("\\n")) sb.Append("\n");
                    }
                    else
                    {
                        var moduleTemp = item.Module;
                        if (!string.IsNullOrEmpty(item.ModuleEx))
                        {
                            moduleTemp = item.ModuleEx;
                        }
                        if (item.Module == "cip_noise 0x80300f00")
                        {

                        }
                        //取值
                        var val =  GetFilerToVal(mmlist, item.ReadAddr, moduleTemp, listStr);
                        string str = item.RearNote.Contains("\\n") ? $"{item.RearNote.Replace("\\n", "")}\n" : item.RearNote;
                        sb.Append($"{item.addr},{val},{str.Trim()}\n");
                        if (item.RearNote.Contains("\\n")) sb.Append("\n");
                       
                       
                    }
                }

                sb.Append("\n\n//IQ_End");
                sb.Append("\n}");
                string pLocalPath = System.IO.Path.GetDirectoryName(dialog.FileName); //获取文件路径
                string pLocalName = $"IQ_Setting_{Path.GetFileNameWithoutExtension(dialog.FileName)}_{DateTime.Now.ToString("yyyyMMddHHmms")}.txt"; //获取文件名
                File.WriteAllText($"{pLocalPath}\\{pLocalName}", sb.ToString(), Encoding.UTF8);
            }
        }


        public string GetFilerToVal(List<string> mlist, string Raddr, string Module,List<notes> listStr)
        {
            string str = "0x";
          


            var msIndex = Array.FindIndex(mlist.ToArray(), t => t.IndexOf(Module, StringComparison.InvariantCultureIgnoreCase) >= 0);
            string NextModule = string.Empty;
            if (msIndex+1<mlist.Count)
            {
                NextModule = mlist[msIndex + 1];
            }
            
            var sindex = Array.FindIndex(listStr.ToArray(), t =>string.IsNullOrEmpty(t.value)&& string.IsNullOrEmpty(t.addr)&& t.note.IndexOf(Module, StringComparison.InvariantCultureIgnoreCase) >= 0);
            if (Module == "TVE")//特殊处理后面的这几个
            {
                sindex = Array.FindLastIndex(listStr.ToArray(), t => string.IsNullOrEmpty(t.value) && string.IsNullOrEmpty(t.addr) && t.note.IndexOf(Module, StringComparison.InvariantCultureIgnoreCase) >= 0);
            }
            var eindex = GetNextIndex(msIndex, sindex, mlist, listStr);
            if (NextModule == "rgb_protect")
            {
                //NextModule = mlist[startIndex + 1];
            }
            if (sindex == -1 )
            {
                return str;
            }
           
            for (int i = sindex; i < eindex; i++)
            {
                if (null!= listStr[i].addr&&listStr[i].addr.Contains(Raddr))
                {
                    return listStr[i].value;
                }
            }
            return str;
        }

        public int GetNextIndex(int msindex,int sindex, List<string> mlist, List<notes> listStr)
        {
            int startIndex = msindex+1;
            int eindex = 0;
            if (startIndex >= mlist.Count)
            {
                eindex = listStr.Count;
            }
            while (startIndex < mlist.Count)
            {
                var  NextModule = mlist[startIndex];
                if (NextModule == "AE speed table"||NextModule.Contains("isp_blc_add"))
                {
                     NextModule = mlist[startIndex+1];
                }
                if (string.IsNullOrEmpty(NextModule))
                {
                    eindex = listStr.Count;
                }
                eindex = Array.FindIndex(listStr.ToArray(), t => string.IsNullOrEmpty(t.value) && string.IsNullOrEmpty(t.addr) && t.note.IndexOf(NextModule, StringComparison.InvariantCultureIgnoreCase) >= 0);
                if (eindex <= sindex)
                {
                    startIndex += 1;
                    if (startIndex>=mlist.Count)
                    {
                        eindex = listStr.Count;
                    }
                }
                else {
                    startIndex += mlist.Count;
                }
            }
            return eindex;
        }
    }

   

}
